/* eslint react/jsx-key: 0 */

import React, { useState } from 'react'
import Highlight, { defaultProps } from 'prism-react-renderer'
import { LiveProvider, LiveEditor, LiveError, LivePreview } from 'react-live'
import { mdx } from '@mdx-js/react'
import { CopyToClipboard } from 'react-copy-to-clipboard';

import { Button, SpaceWraper, Modal, Alert } from "@teach_wmg_21";

const CodeBlockStyle = {
  square: {
    width: '50px',
    height: '50px',
    backgroundColor: 'orangered'
  }
}



export default (props) => {

  console.log(props, "============CodeBlock============");

  var { children, className, live, render, codeDefaultShow = false } = props;

  const language = className.replace(/language-/, '')

  const [showEditor, SetShowEditor] = useState(codeDefaultShow);

  if (live) {
    return (
      <div className="code_block_container">
        <LiveProvider
          code={children.trim()}
          // transformCode={code => code}
          scope={{ mdx, Button, SpaceWraper, Modal, Alert, CodeBlockStyle,CopyToClipboard}}
        >
          <LivePreview className="LivePreview" />
          <div className="code_block_tool">
            <button onClick={() => SetShowEditor(!showEditor)}>源码</button>
            <CopyToClipboard className="see_code_btn" text={children.trim()}
              onCopy={() => Alert.info({
                content: '复制成功',
                duration: 0.4
              })}>
              <button>复制</button>
            </CopyToClipboard>
          </div>
          {
            showEditor && <LiveEditor className="LiveEditor" style={{ marginTop: '0px', backgroundColor: 'black', caretColor: '#f8f8f8' }} />
          }
          <LiveError />
        </LiveProvider>
      </div>
    )
  }

  if (render) {
    return (
      <div style={{ marginTop: '40px' }}>
        <LiveProvider code={children}>
          <LivePreview />
        </LiveProvider>
      </div>
    )
  }

  return (
    <Highlight {...defaultProps} code={children.trim()} language={language}>
      {({ className, style, tokens, getLineProps, getTokenProps }) => (
        <pre className={className} style={{ ...style, padding: '20px' }}>
          {tokens.map((line, i) => (
            <div key={i} {...getLineProps({ line, key: i })}>
              {line.map((token, key) => (
                <span key={key} {...getTokenProps({ token, key })} />
              ))}
            </div>
          ))}
        </pre>
      )}
    </Highlight>
  )
}
